import React, { useState, useMemo } from 'react';
import { Form, AutoComplete, Button, Space, message } from 'antd';

import store from '@/store';
import { setDefaultConfig } from '@/request/api/home';
import { observer } from 'mobx-react-lite';

import Icon from '@/component/Icon';
import useForm from '@/hooks/useForm';
import Styles from './index.module.less';

interface FormSettingProps {
    toggleSetting: (visible: boolean) => unknown;
}

export default React.memo<FormSettingProps>(
    observer((props) => {
        const { app } = store.useStore();
        const [searchPrinterKey, setSearchPrinterKey] = useState('');
        const [form, printerList] = useForm({
            searchPrinterKey
        });

        const onFinish = ({ printer }: { printer: string }) => {
            setDefaultConfig({ printer })
                .then((res) => {
                    if (res.data.code === 200) {
                        message.success(`设置成功！`);
                        app.fetchPrinterList();
                        props.toggleSetting(false);
                        return;
                    } else {
                        message.error(`设置失败：${res.data.result}`);
                    }
                })
                .catch((e) => {
                    message.error(`设置失败${e.message || e}`);
                });
        };

        const showWarningTips = useMemo(() => {
            return !app.defaultPrinter;
        }, [app.defaultPrinter]);

        return (
            <>
                <Form
                    rootClassName={Styles.form}
                    form={form}
                    name="setting"
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    className={Styles.form}
                    onFinish={onFinish}
                    autoComplete="off"
                >
                    <Form.Item
                        label="默认打印机"
                        name="printer"
                        rules={[
                            {
                                required: true,
                                message: '请选择一台打印机'
                            },
                            {
                                validator: async (_, printer) => {
                                    if (
                                        printer &&
                                        !app.printerList.result.find(
                                            (item) => item.value === printer
                                        )
                                    )
                                        return Promise.reject(
                                            `打印机：${printer} 不在线，请重新搜索后试试`
                                        );
                                }
                            }
                        ]}
                    >
                        <AutoComplete
                            allowClear={true}
                            disabled={app.isAwakenFail}
                            placeholder="请选择一台默认的打印机"
                            onSearch={(key: string) => setSearchPrinterKey(key)}
                            options={printerList}
                        />
                    </Form.Item>
                    <Form.Item
                        wrapperCol={{ span: 24 }}
                        className={Styles.formAction}
                    >
                        <Space size={8}>
                            <Button
                                type="primary"
                                htmlType="submit"
                                loading={app.loadingTextOption.loading}
                                icon={<Icon name="icon-confirm" />}
                            >
                                {app.loadingTextOption.text || '确认'}
                            </Button>
                            <Button
                                loading={app.loadingTextOption.loading}
                                icon={<Icon name="icon-search" />}
                                onClick={app.fetchPrinterOption}
                            >
                                {app.loadingTextOption.text ||
                                    '重置并搜索打印机'}
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
                {showWarningTips && (
                    <section className={Styles.warningTips}>
                        注意：请设置默认打印机后才能打印文件
                    </section>
                )}
            </>
        );
    })
);
